<?php

namespace App\Orchid\Layouts\Setting;

use App\Models\Setting;
use Orchid\Screen\TD;
use Orchid\Screen\Actions\Link;
use Orchid\Screen\Layouts\Table;

class SettingListLayout extends Table
{
    /**
     * Data source.
     *
     * The name of the key to fetch it from the query.
     * The results of which will be elements of the table.
     *
     * @var string
     */
    protected $target = 'settings';

    /**
     * Get the table cells to be displayed.
     *
     * @return TD[]
     */
    protected function columns(): iterable
    {
        return [
            TD::make('key', '设置键')
                ->sort()
                ->filter(TD::FILTER_TEXT)
                ->render(function (Setting $setting) {
                    return Link::make($setting->key)
                        ->route('platform.settings.edit', $setting);
                }),
                
            TD::make('name', '设置名称')
                ->sort()
                ->filter(TD::FILTER_TEXT),
                
            TD::make('value', '设置值')
                ->render(function (Setting $setting) {
                    $value = $setting->value;
                    if (strlen($value) > 50) {
                        return substr($value, 0, 50) . '...';
                    }
                    return $value;
                }),
                
            TD::make('type', '类型')
                ->render(function (Setting $setting) {
                    return match($setting->type ?? 'text') {
                        'text' => '文本',
                        'textarea' => '多行文本',
                        'number' => '数字',
                        'boolean' => '布尔值',
                        'select' => '选择',
                        'json' => 'JSON',
                        default => $setting->type,
                    };
                }),
                
            TD::make('group', '分组')
                ->render(function (Setting $setting) {
                    return $setting->group ?: '默认';
                }),
                
            TD::make('created_at', '创建时间')
                ->sort()
                ->render(function (Setting $setting) {
                    return $setting->created_at->format('Y-m-d H:i');
                }),
                
            TD::make('操作')
                ->align(TD::ALIGN_CENTER)
                ->width('150px')
                ->render(function (Setting $setting) {
                    return Link::make('编辑')
                        ->icon('pencil')
                        ->route('platform.settings.edit', $setting);
                }),
        ];
    }
}